package com.codingfuture.st200.service;

import net.dreamlu.iot.mqtt.spring.client.MqttClientTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;


@Service
public class MainService {
    private static final Logger logger = LoggerFactory.getLogger(MainService.class);
    @Autowired
    private MqttClientTemplate client;

    /**
     * 发布
     *
     * @return
     */
    public boolean publish() {
        client.publish("/topic/publish_temperature", ("" +
                "{\n" +
                "        \"messageid\": \"3FBD8A5D-9824-D355-EF7A-B31A609522CC\",\n" +
                "        \"param\": {\n" +
                "            \"type\": \"info\"\n" +
                "        }\n" +
                "}").getBytes(StandardCharsets.UTF_8));
        return true;
    }

    /**
     * 订阅
     *
     * @return
     */
    public boolean sub() {
        client.subQos0("/topic/subscribe_temperature", (context, topic, message, payload) -> {
            String s = new String(payload, StandardCharsets.UTF_8);
            logger.info(topic + '\t' + s);
        });
        return true;
    }

}
